from django.http import JsonResponse
from aaa.utils import response_code
from aaa.models import Ad, CarefullyChosen, Goods, MallModels,Categories,StoreService,Params,GoodsProduct,\
    StoreService,Customer,FootPoint,Collect,CustomerAddress,IAS,GoodsSpecification,Cart,GoodsOrder,GoodsOrderGoods
import json
from django.db.models import Sum
from aaa.utils.commons import get_api_user_id,pay_complet_method,get_status_text
from django.conf import settings
from django.core.paginator import Paginator

def index_data(request,*args,**kwargs):
    carouselList = Ad.objects.filter(position=0).values('image','link')
    carouselListM = Ad.objects.filter(position=1).values('image','link')
    chosenList = []
    goods_ids = []
    chosens = CarefullyChosen.objects.all()
    for item in chosens:
        temp_dic = {}
        temp_dic['id'] = item.id
        temp_dic['image'] = item.image
        for goods in item.goods.values('goods_id'):
            goods_ids.append(goods['goods_id'])
        goods_li = Goods.objects.filter(goods_id__in=goods_ids, is_delete=False, is_onsale=True).values('goods_id', 'pics', 'goods_name', 'goods_price')
        temp_dic['goods'] = list(goods_li)
        chosenList.append(temp_dic)
    goodsList = Goods.objects.filter(is_delete=False, is_onsale=True, is_promote=True).values('goods_id', 'pics', 'goods_name', 'goods_price')
    mallmodelsList = MallModels.objects.all().values('id', 'name', 'image', 'link', 'type')
    res = {
        'errno': response_code.IS_SUCCESS,
        'statusCode': 200,
        'errMsg': '数据获取成功',
        'data': {
            'carouselList': list(carouselList),
            'carouselListM': list(carouselListM),
            'carefullychosenList': chosenList,
            'goodsList': list(goodsList),
            'mallmodelsList': list(mallmodelsList)
        }
    }
    return JsonResponse(res)

def category_list(request,*args,**kwargs):
    categories = Categories.objects.all()
    category_li = []
    for item in categories:
        temp_dic = {}
        temp_dic['id'] = item.cat_id
        temp_dic['name'] = item.cat_name
        temp_dic['cat_level'] = item.cat_level
        temp_dic['pid'] = item.cat_pid
        temp_dic['image'] = item.image
        # temp_dic['picture'] = item.image
        category_li.append(temp_dic)

    res = {
        'errno': response_code.IS_SUCCESS,
        'statusCode': 200,
        'errMsg': '数据获取成功',
        'data': {
            'category_list': category_li
        }
    }
    return JsonResponse(res)

def goods_list(request,*args,**kwargs):
    print('goods_list request.GET', request.GET)
    fid = int(request.GET.get('fid', 0))
    sid = int(request.GET.get('sid', 0))
    tid = int(request.GET.get('tid', 0))
    print('fid',fid,'sid',sid,'tid',tid)

    goods_li = Goods.objects.filter(is_delete=False, is_onsale=True).values('goods_id', 'goods_name', 'pics', 'goods_price', 'sale_num')
    if tid:
        goods_li = goods_li.filter(goods_cat=tid)
    else:
        if sid:
            s_list = [ item.cat_id for item in Categories.objects.filter(cat_pid=sid)]
            goods_li = goods_li.filter(goods_cat__in=s_list)
        else:
            if fid:
                # 这个一级类目下的二级类目
                x_list = [ item.cat_id for item in Categories.objects.filter(cat_pid=fid)]
                print('x_list', x_list)
                t_list = [ item.cat_id for item in Categories.objects.filter(cat_pid__in=x_list) ]
                print('t_list', t_list)
                goods_li = goods_li.filter(goods_cat__in=t_list)

    res = {
        'errno': response_code.IS_SUCCESS,
        'statusCode': 200,
        'errMsg': '数据获取成功',
        'data': {
            'goods_list': list(goods_li)
        }
    }
    return JsonResponse(res)

def ias_list(request,*args,**kwargs):
    print('ias_list request.GET', request.GET)
    fid = int(request.GET.get('fid', 0))
    sid = int(request.GET.get('sid', 0))
    tid = int(request.GET.get('tid', 0))
    print('fid',fid,'sid',sid,'tid',tid)

    ias_li = IAS.objects.all().values('id', 'name', 'server', 'path','image','xxx','version')
    if tid:
        ias_li = ias_li.filter(ias_cat=tid)
    else:
        if sid:
            s_list = [ item.cat_id for item in Categories.objects.filter(cat_pid=sid)]
            ias_li = ias_li.filter(ias_cat__in=s_list)
        else:
            if fid:
                # 这个一级类目下的二级类目
                x_list = [ item.cat_id for item in Categories.objects.filter(cat_pid=fid)]
                print('x_list', x_list)
                t_list = [ item.cat_id for item in Categories.objects.filter(cat_pid__in=x_list) ]
                print('t_list', t_list)
                ias_li = ias_li.filter(ias_cat__in=t_list)

    res = {
        'errno': response_code.IS_SUCCESS,
        'statusCode': 200,
        'errMsg': '数据获取成功',
        'data': {
            'ias_list': list(ias_li)
        }
    }
    return JsonResponse(res)

def goods_detail(request,*args,**kwargs):
    user_id = get_api_user_id(request)
    print('goods_detail user_id',user_id)
    if user_id:
        customerObj = Customer.objects.get(user_id=user_id)
        hasLogin = True
    else:
        customerObj = None
        hasLogin = False
    goods_id = int(request.GET.get('goods_id', 0))
    if goods_id:
        goodsObj = Goods.objects.get(goods_id=goods_id, is_delete=False)
        goodsObj.read_num = goodsObj.read_num + 1
        goodsObj.save()
        attributes = Params.objects.filter(attr_sel=1,cat_id_id=goodsObj.goods_cat).values('attr_name','attr_vals')
        if goodsObj.ori_price > 0:
            discount_num = round((goodsObj.goods_price/goodsObj.ori_price)*10, 1)
        else:
            discount_num = 0

        # 总库存
        goodsproducts = GoodsProduct.objects.filter(goods=goodsObj)
        goods_number_sum = goodsproducts.aggregate(number_sum=Sum('number'))['number_sum']
        if not goods_number_sum:
            goods_number_sum = 0
        # 获取服务
        storeservices = StoreService.objects.all().values('name')

        #添加足迹
        if customerObj:
            FootPoint.objects.filter(customer=customerObj, goods=goodsObj).delete()
            FootPoint().footpoint_save(customerObj, goodsObj)

        # 获取收藏状态
        if customerObj:
            try:
                collectObj = Collect.objects.get(goods_id=goods_id, customer=customerObj)
                favorite = True
            except:
                favorite = False
        else:
            favorite = False

        # 获取规格信息
        # 从商品的分类参数取静态属性不合适
        # goodsObj = Goods.objects.get(goods_id=goods_id)
        # goodsParams = Params.objects.filter(attr_sel=1, cat_id_id=goodsObj.goods_cat)
        # goodsspecifications = []
        # for i in goodsParams:
        #     for val in i.attr_vals.split(' '):
        #         speci_dict = {}
        #         speci_dict['specification'] = i.attr_name
        #         speci_dict['value'] = val
        #         goodsspecifications.append(speci_dict)
        goodsspecifications = GoodsSpecification.objects.filter(goods=goodsObj)
        goodsspecification_list = []
        specification_name_list = []
        for item in goodsspecifications:
            temp_dic = {}
            name_temp = item.specification
            if name_temp in specification_name_list:
                index_arr = specification_name_list.index(name_temp)
                goodsspecification_list[index_arr]['values'].append({"checked": False, "value": item.value})
            else:
                specification_name_list.append(name_temp)
                temp_list = []
                temp_list.append({"checked": False, "value": item.value})
                temp_dic['name'] = name_temp
                temp_dic['values'] = temp_list
                goodsspecification_list.append(temp_dic)

        # 获取产品信息
        products_list = []
        for iitem in goodsproducts:
            itemp_dic = {}
            itemp_dic['id'] = iitem.id
            itemp_dic['specifications'] = iitem.specifications
            itemp_dic['price'] = iitem.price
            itemp_dic['number'] = iitem.number
            itemp_dic['product_image_url'] = iitem.goods_image
            products_list.append(itemp_dic)

        res = {
            'errno': response_code.IS_SUCCESS,
            'statusCode': 200,
            'errMsg': '数据获取成功',
            'data': {
                'hasLogin': hasLogin,
                'id': goodsObj.goods_id,
                'name': goodsObj.goods_name,
                # 'goods_sn': goodsObj.goods_sn,
                'goods_image': goodsObj.pics,
                'gallery': goodsObj.pics,
                'is_onsale': goodsObj.is_onsale,
                # 'unit': goodsObj.unit,
                'price': goodsObj.goods_price,
                'ori_price': goodsObj.ori_price,
                'detail': goodsObj.goods_introduce,
                'sale_num': goodsObj.sale_num,
                'read_num': goodsObj.read_num,
                'discount_num': discount_num,
                'number': goods_number_sum,
                'attributes': list(attributes),
                'storeservices': list(storeservices),
                'favorite': favorite,
                'specifications': goodsspecification_list,
                'products': products_list
            }
        }
    else:
        res = {
            'errno': response_code.NO_DATA,
            'statusCode': 200,
            'errMsg': '没有获取到数据',
            'data': {

            }
        }

    return JsonResponse(res)

def my_page_data(request,*args,**kwargs):
    user_id = get_api_user_id(request)
    if user_id:
        customerObj = Customer.objects.get(user_id=user_id)
        hasLogin = True
    else:
        customerObj = None
        hasLogin = False

    if customerObj:
        footpoints = FootPoint.objects.filter(customer=customerObj).values('id', 'goods_id', 'goods__pics')
        remaining_sum = customerObj.remaining_sum
        accumulate = customerObj.accumulate
    else:
        footpoints = []
        remaining_sum = 0
        accumulate = 0

    res = {
        'errno': response_code.IS_SUCCESS,
        'statusCode': 200,
        'errMsg': '数据获取成功',
        'data': {
            'footpoint_list': list(footpoints),
            'remaining_sum': remaining_sum,
            'accumulate': accumulate,
            'hasLogin': hasLogin
        }
    }
    return JsonResponse(res)

def collect_add(request,*args,**kwargs):
    user_id = get_api_user_id(request)
    if not user_id:
        res = {
            'errno': response_code.NO_LOGIN,
            'statusCode': 200,
            'errMsg': '没有登录',
        }
        return JsonResponse(res)
    goods_id = int(request.GET.get('goods_id', 0))
    print('collect_add goods_id',goods_id)
    if goods_id:
        customerObj = Customer.objects.get(user_id=user_id)
        goodsObj = Goods.objects.get(goods_id=goods_id)
        try:
            collectObj = Collect.objects.get(goods_id=goods_id, customer=customerObj)
            collectObj.delete()
            errMsg = '取消收藏成功'
        except:
            Collect().collect_save(customerObj, goodsObj)
            errMsg = '收藏成功'

        res = {
            'errno': response_code.IS_SUCCESS,
            'statusCode': 200,
            'errMsg': errMsg,
            'data': {

            }
        }
    else:
        res = {
            'errno': response_code.NO_DATA,
            'statusCode': 200,
            'errMsg': '没有获取到商品',
            'data': {

            }
        }

    return JsonResponse(res)

def collect_list(request,*args,**kwargs):
    user_id = get_api_user_id(request)
    if not user_id:
        res = {
            'errno': response_code.NO_LOGIN,
            'statusCode': 200,
            'errMsg': '没有登录',
        }
        return JsonResponse(res)
    collects = Collect.objects.filter(customer__user_id=user_id).values('id', 'goods_id', 'goods__goods_name', 'goods__pics', 'goods__goods_price')

    res = {
        'errno': response_code.IS_SUCCESS,
        'statusCode': 200,
        'errMsg': '数据获取成功',
        'data': {
            'collect_list': list(collects)
        }
    }
    return JsonResponse(res)

def address_list(request,*args,**kwargs):
    user_id = get_api_user_id(request)
    if not user_id:
        res = {
            'errno': response_code.NO_LOGIN,
            'statusCode': 200,
            'errMsg': '没有登录',
        }
        return JsonResponse(res)
    address = CustomerAddress.objects.filter(customer__user_id=user_id, is_delete=False).values('id', 'name', 'phone_number', 'address', 'address_detail', 'longitude', 'latitude', 'is_default')

    res = {
        'errno': response_code.IS_SUCCESS,
        'statusCode': 200,
        'errMsg': '数据获取成功',
        'data': {
            'address_list': list(address)
        }
    }
    return JsonResponse(res)

def address_create(request,*args,**kwargs):
    user_id = get_api_user_id(request)
    if not user_id:
        res = {
            'errno': response_code.NO_LOGIN,
            'statusCode': 200,
            'errMsg': '没有登录',
        }
        return JsonResponse(res)
    json_data = json.loads(request.body)
    address_id = int(json_data['id'])
    print('address_create address_id',args,kwargs,request.body)
    if address_id:
        # 编辑
        addressObj = CustomerAddress.objects.get(id=address_id, customer__user_id=user_id)
        addressObj.address_save(request, user_id)
    else:
        #创建、新增
        CustomerAddress().address_save(request, user_id)

    res = {
        'errno': response_code.IS_SUCCESS,
        'statusCode': 200,
        'errMsg': '操作成功',
        'data': {

        }
    }
    return JsonResponse(res)

def address_delete(request,*args,**kwargs):
    user_id = get_api_user_id(request)
    if not user_id:
        res = {
            'errno': response_code.NO_LOGIN,
            'statusCode': 200,
            'errMsg': '没有登录',
        }
        return JsonResponse(res)
    json_data = json.loads(request.body)
    address_id = int(json_data['id'])
    if address_id:
        # 开始删除
        addressObj = CustomerAddress.objects.get(id=address_id, customer__user_id=user_id)
        # 逻辑删除
        addressObj.is_delete = True
        addressObj.save()
        res = {
            'errno': response_code.IS_SUCCESS,
            'statusCode': 200,
            'errMsg': '删除成功',
            'data': {

            }
        }

    else:
        res = {
            'errno': response_code.NO_DATA,
            'statusCode': 200,
            'errMsg': '无法获取您想要删除的记录',
            'data': {

            }
        }

    return JsonResponse(res)

def cart_add(request,*args,**kwargs):
    user_id = get_api_user_id(request)
    if not user_id:
        res = {
            'errno': response_code.NO_LOGIN,
            'statusCode': 200,
            'errMsg': '没有登录',
        }
        return JsonResponse(res)
    json_data = json.loads(request.body)
    cart_id = int(json_data['id'])
    number = int(json_data['number'])
    goods_id = int(json_data['goods_id'])
    specifications = json_data['specifications']
    if cart_id:
        # 编辑
        cartObj = Cart.objects.get(id=cart_id)
        cartObj.number = number
        cartObj.save()
        errMsg = '修改成功'
    else:
        # 添加
        if Cart.objects.filter(customer__user_id=user_id, goods_id=goods_id, specifications=json.dumps(specifications), is_delete=False):
            #已经添加过了
            errMsg = '已经添加过了'
        else:
            Cart().cart_save(user_id, goods_id, specifications, number)
            errMsg = '加入购物车成功'
    res = {
        'errno': response_code.IS_SUCCESS,
        'statusCode': 200,
        'errMsg': errMsg,
        'data': {

        }
    }

    return JsonResponse(res)

def cart_list(request,*args,**kwargs):
    user_id = get_api_user_id(request)
    if user_id:
        hasLogin = True
    else:
        hasLogin = False
    carts = Cart.objects.filter(customer__user_id=user_id, is_delete=False, goods__isnull=False, goods__is_onsale=True)
    print('carts',carts)
    cart_li = []
    for item in carts:
        print(item.goods_id,' '.join(json.loads(item.specifications)))
        productObj = GoodsProduct.objects.filter(goods=item.goods_id, specifications=' '.join(json.loads(item.specifications)))
        print('productObj',productObj)
        if productObj:
            temp_dic = {}
            temp_dic['id'] = item.id
            temp_dic['goods_id'] = item.goods_id
            temp_dic['name'] = item.goods.goods_name
            temp_dic['price'] = item.goods.goods_price
            temp_dic['goods_image'] = settings.PIC_URL + item.goods.pics[0]['pic']
            temp_dic['specifications'] = json.loads(item.specifications)
            temp_dic['number'] = item.number
            temp_dic['stock'] = productObj[0].number
            temp_dic['checked'] = True
            cart_li.append(temp_dic)
        else:
            pass
            # item.is_delete = True
            # item.save()

    res = {
        'errno': response_code.IS_SUCCESS,
        'statusCode': 200,
        'errMsg': '数据获取成功',
        'data': {
            'cart_list': cart_li,
            'hasLogin': hasLogin
        }
    }
    return JsonResponse(res)

def cart_delete(request,*args,**kwargs):
    user_id = get_api_user_id(request)
    if not user_id:
        res = {
            'errno': response_code.NO_LOGIN,
            'statusCode': 200,
            'errMsg': '没有登录',
        }
        return JsonResponse(res)
    json_data = json.loads(request.body)
    cart_id = int(json_data['id'])
    if cart_id:
        # 开始删除
        cartObj = Cart.objects.get(id=cart_id, customer__user_id=user_id, is_delete=False)
        # 真删除
        cartObj.delete()
        res = {
            'errno': response_code.IS_SUCCESS,
            'statusCode': 200,
            'errMsg': '删除成功',
            'data': {

            }
        }

    else:
        carts = Cart.objects.filter(customer__user_id=user_id, is_delete=False)
        carts.delete()
        res = {
            'errno': response_code.IS_SUCCESS,
            'statusCode': 200,
            'errMsg': '清空成功',
            'data': {

            }
        }

    return JsonResponse(res)

def submit_order(request,*args,**kwargs):
    user_id = get_api_user_id(request)
    if not user_id:
        res = {
            'errno': response_code.NO_LOGIN,
            'statusCode': 200,
            'errMsg': '没有登录',
        }
        return JsonResponse(res)
    json_data = json.loads(request.body)
    is_cart = int(json_data['is_cart'])
    if is_cart:
        cartList = json_data['cartList']
        if len(cartList):
            orderObj = GoodsOrder().goodsorder_add(user_id)
            goods_total_price = 0
            for goods in cartList:
                if goods['number'] > 0:
                    goodsObj = Goods.objects.get(goods_id=goods['goods_id'])
                    print('goods specifications',goods['specifications'])
                    productObj = GoodsProduct.objects.get(goods=goodsObj, specifications=' '.join(goods['specifications']))
                    if productObj.number < goods['number']:
                        return JsonResponse({'errno': response_code.SYS_ERR, 'statusCode': 200, 'errMsg': '库存不够了'})
                    GoodsOrderGoods().goods_add(order=orderObj, goodsObj=goodsObj, productObj=productObj, amount=goods['number'],
                                                specifications=json.dumps(goods['specifications']))
                    temp_price = round(goods['number'] * productObj.price, 2)
                    goods_total_price = round(goods_total_price + temp_price, 2)
                    productObj.number = productObj.number - goods['number']
                    goodsObj.sale_num = goodsObj.sale_num + goods['number']
                    goodsObj.save()
                    productObj.save()
                    Cart.objects.filter(goods_id=goods['goods_id']).delete()
            orderObj.total_price = goods_total_price
            orderObj.save()
            order_id = orderObj.id
            errno = response_code.IS_SUCCESS
            errMsg = '提交成功'
        else:
            errno = response_code.NO_DATA
            errMsg = '您没有选择商品'
            order_id = ''
    else:
        number = int(json_data['number'])
        goods_id = int(json_data['goods_id'])
        specifications = json_data['specifications']
        goodsObj = Goods.objects.get(goods_id=goods_id)
        print('submit order 2',number,goodsObj,specifications)
        productObj = GoodsProduct.objects.get(goods=goodsObj, specifications=' '.join(specifications))
        if productObj.number < number:
            return JsonResponse({'errno': response_code.SYS_ERR, 'statusCode': 200, 'errMsg': '库存不够了'})
        orderObj = GoodsOrder().goodsorder_add(user_id)
        if orderObj.id:
            GoodsOrderGoods().goods_add(order=orderObj, goodsObj=goodsObj, productObj=productObj, amount=number, specifications=json.dumps(specifications))
            orderObj.total_price = round(productObj.price*number, 2)
            orderObj.save()

            productObj.number = productObj.number - number
            goodsObj.sale_num = goodsObj.sale_num + number
            goodsObj.save()
            productObj.save()
            errno = response_code.IS_SUCCESS
            errMsg = '提交成功'
            order_id = orderObj.id
        else:
            errno = response_code.SYS_ERR
            errMsg = '写入订单错误'
            order_id = ''


    res = {
        'errno': errno,
        'statusCode': 200,
        'errMsg': errMsg,
        'data': {
            'order_id': order_id
        }
    }

    return JsonResponse(res)

def get_order_detail(request,*args,**kwargs):
    user_id = get_api_user_id(request)
    if not user_id:
        res = {
            'errno': response_code.NO_LOGIN,
            'statusCode': 200,
            'errMsg': '没有登录',
        }
        return JsonResponse(res)
    order_id = request.GET.get('order_id', False)
    if order_id:
        orderObj = GoodsOrder.objects.get(id=order_id, customer__user_id=user_id)
        ordergoods = GoodsOrderGoods.objects.filter(order=orderObj)
        goods_li = []
        for item in ordergoods:
            temp_dic = {}
            temp_dic['name'] = item.name
            temp_dic['goods_image'] = item.goods_image
            temp_dic['amount'] = item.amount
            temp_dic['price'] = item.price
            temp_dic['specifications'] = json.loads(item.specifications)
            goods_li.append(temp_dic)
        if not orderObj.address_obj:
            try:
                addressObj = CustomerAddress.objects.get(customer__user_id=user_id,is_delete=False,is_default=True)
            except:
                addresses = CustomerAddress.objects.filter(customer__user_id=user_id,is_delete=False)
                if addresses:
                    addressObj = addresses[0]
                else:
                    addressObj = None
        else:
            addressObj =orderObj.address_obj
        if addressObj:
            adressobj_id = addressObj.id
            contacts_name = addressObj.name
            phone_number = addressObj.phone_number
            address = addressObj.address + addressObj.address_detail
            longitude = addressObj.longitude
            latitude = addressObj.latitude
        else:
            adressobj_id = 0
            contacts_name = ''
            phone_number = ''
            address = ''
            longitude = ''
            latitude = ''
        if orderObj.express_time:
            express_time = orderObj.express_time.strftime('%Y-%m-%d %H:%M:%S')
        else:
            express_time = ''

        res = {
            'errno': response_code.IS_SUCCESS,
            'statusCode': 200,
            'errMsg': '删除成功',
            'data': {
                'order_id': orderObj.id,
                'adressobj_id': adressobj_id,
                'contacts_name': contacts_name,
                'phone_number': phone_number,
                'address': address,
                'longitude': longitude,
                'latitude': latitude,
                'total_price': orderObj.total_price,
                'actual_price': orderObj.actual_price,
                'order_remark': orderObj.order_remark,
                'status': orderObj.status,
                'status_text': get_status_text(orderObj.status),
                'express_sn': orderObj.express_sn,
                'express_name': orderObj.express_name,
                'express_time': express_time,
                'is_pay': orderObj.is_pay,
                'create_date': orderObj.create_date.strftime('%Y-%m-%d %H:%M:%S'),
                'goods_list': goods_li
            }
        }

    else:
        res = {
            'errno': response_code.NO_DATA,
            'statusCode': 200,
            'errMsg': '找不到记录',
            'data': {

            }
        }

    return JsonResponse(res)

def save_order_detail(request,*args,**kwargs):
    user_id = get_api_user_id(request)
    if not user_id:
        res = {
            'errno': response_code.NO_LOGIN,
            'statusCode': 200,
            'errMsg': '没有登录',
        }
        return JsonResponse(res)
    json_data = json.loads(request.body)
    contacts_name = json_data['contacts_name']
    phone_number = json_data['phone_number']
    address = json_data['address']
    longitude = json_data['longitude']
    latitude = json_data['latitude']
    order_id = json_data['order_id']
    order_remark = json_data['order_remark']
    if order_id:
        orderObj = GoodsOrder.objects.get(id=order_id, customer__user_id=user_id)
        if orderObj.is_pay:
            return JsonResponse({'errno': response_code.SYS_ERR, 'statusCode': 200, 'errMsg': '您已经支付过了'})
        orderObj.contacts_name = contacts_name
        orderObj.phone_number = phone_number
        orderObj.address = address
        orderObj.longitude = longitude
        orderObj.latitude = latitude
        orderObj.order_remark = order_remark
        orderObj.actual_price = orderObj.total_price
        orderObj.status = 1

        if orderObj.actual_price <=0:
            orderObj.actual_price = 0
            pay_complet_method(orderObj)
        orderObj.save()

        res = {
            'errno': response_code.IS_SUCCESS,
            'statusCode': 200,
            'errMsg': '保存成功',
            'data': {
                'actual_price': orderObj.actual_price
            }
        }
    else:
        res = {
            'errno': response_code.NO_DATA,
            'statusCode': 200,
            'errMsg': '没有找到数据',
            'data': {

            }
        }

    return JsonResponse(res)

def order_list(request,*args,**kwargs):
    user_id = get_api_user_id(request)
    if not user_id:
        res = {
            'errno': response_code.NO_LOGIN,
            'statusCode': 200,
            'errMsg': '没有登录',
        }
        return JsonResponse(res)
    page = int(request.GET.get('page', 0))
    limit = int(request.GET.get('limit', 10))
    state = int(request.GET.get('state', 0))
    orders = GoodsOrder.objects.filter(customer__user_id=user_id, is_delete=False)
    if state == 1:
        orders = orders.filter(status=1)
    elif state == 2:
        orders = orders.filter(status__in=[2,3])
    elif state == 3:
        orders = orders.filter(status=6)
    elif state == 4:
        orders = orders.filter(status__in=[8, 9])

    paginator = Paginator(orders, limit)

    if page < 1:
        current_page = 1
    elif page > paginator.num_pages:
        current_page = paginator.num_pages
    else:
        current_page = page

    page_order = paginator.page(current_page)
    orderList = []
    for item in page_order:
        temp_dic = {}
        temp_dic['id'] = item.id
        temp_dic['status'] = item.status
        temp_dic['status_text'] = get_status_text(item.status)
        temp_dic['create_date'] = item.create_date.strftime('%Y-%m-%d %H:%M:%S')
        temp_dic['actual_price'] = item.actual_price
        ordergoods = GoodsOrderGoods.objects.filter(order=item)
        if ordergoods.count() == 1:
            goodsObj = ordergoods[0]
            temp_list = []
            goods_dic = {
                'name': goodsObj.name,
                'specifications': json.loads(goodsObj.specifications),
                'price': goodsObj.price,
                'amount': goodsObj.amount,
                'goods_image': goodsObj.goods_image
            }
            temp_list.append(goods_dic)
            temp_dic['goods_list'] = temp_list
        else:
            temp_dic['goods_list'] = list(ordergoods.values('goods_image'))
        orderList.append(temp_dic)

    res = {
        'errno': response_code.IS_SUCCESS,
        'statusCode': 200,
        'errMsg': '数据获取成功',
        'data': {
            'orderList': list(orderList),
            'page_max': paginator.num_pages
        }
    }
    return JsonResponse(res)